import pymongo
from urllib import parse


username = parse.quote_plus('admin')  # 对用户名进行编码
password = parse.quote_plus('123456')  # 对密码进行编码
host = "120.26.238.200"
port = "27017"
# mongo = pymongo.MongoClient('mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, database))
mongo = pymongo.MongoClient(host=host, port=27017, username=username, password=password)
mongodb = mongo["cwapi"]    # 数据库名称
monge_comm = mongodb["comments"]    # 集合名称


if __name__ == '__main__':
    # print(username)
    # print(password)

    print(mongo)
    print(mongodb)
    print(monge_comm)

    # 测试集合
    test_coll = mongodb["test"]

    '''插入数据'''
    # document = {"name": "xiaoming", "mobile": "13012345678", "age": 16}
    # ret = test_coll.insert_one(document)
    # print(ret.inserted_id)  # 返回InsertOneResult对象
    # # 插入文档时，如果没有指定_id，将自动分配一个唯一的id。
    #
    # document_list = [
    #     {"name": "xiaoming", "mobile": "13033345678", "age": 17},
    #     {"name": "xiaohong", "mobile": "13044345678", "age": 18},
    #     {"name": "xiaohei", "mobile": "13612345678", "age": 18},
    # ]
    # ret = test_coll.insert_many(document_list)
    # print(ret)

    for row in test_coll.find({"age": {"$gt": 17}}, {"_id": 0, "name": 1, "age": 1}):
        print(row)

    for row in test_coll.find({"mobile": "13033345678"}, {"_id": 0, "name": 1, "mobile": 1}):
        print(row)

    for row in test_coll.find():
        print(row)